using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Diagnostics;

namespace ManagedServicesLauncher
{
    class Program
    {
        [MTAThread]
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                StartServices();
                SignalStarted(uint.Parse(args[0]));
            }
        }

        private static void StartServices()
        {
            RegistryKey mainkey = Registry.LocalMachine.OpenSubKey("Software\\ManagedServices", true);
            if (mainkey == null)
            {
                return;
            }
            RegistryKey servicekey;
            Process serviceStarter;
            //Checks for registered services
            foreach (string keyname in mainkey.GetSubKeyNames())
            {
                try
                {
                    servicekey = Registry.LocalMachine.OpenSubKey("Software\\ManagedServices\\" + keyname);
                    //Checks if registered Service has set StartType = 1(StartType.Automatic).
                    if ((int)servicekey.GetValue("StartType", 0) == 1)
                    {
                        serviceStarter = new Process();
                        serviceStarter.StartInfo = new ProcessStartInfo((string)servicekey.GetValue("Executable"), "");
                        serviceStarter.StartInfo.UseShellExecute = true;
                        serviceStarter.Start();
                    }
                }
                catch
                {
                    //Nothing in here as the next service shall be tried to be started                    
                }
            }
        }
        /// <summary>
        /// On system startup this method has to be called to return the DWORD, which has been provided by the system as command line parameter.
        /// The method is called, when the application has loaded the services correctly and is ready.
        /// </summary>
        /// <param name="dword"></param>
        [DllImport("coredll")]
        public extern static void SignalStarted(uint dword);
    }

}
